/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.wholeconsulting.pacc.gui.utils.frame;


import ar.com.wholeconsulting.pacc.persistance.JPASession;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityTransaction;
import javax.swing.JDialog;

/**
 *
 * @author Duco Pablo
 */
public abstract class SaveOnCloseDialog extends JDialog {

    private EntityTransaction transaction;
    protected boolean ok;
    protected boolean isNew;

    public SaveOnCloseDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosed(java.awt.event.WindowEvent evt) {
                ok = false;
                setVisible(false);
            }
        });
        transaction = JPASession.getInstance().getManager().getTransaction();
        try {
            transaction.begin();
        } catch (java.lang.IllegalStateException ex) {
            transaction.rollback();
            transaction = JPASession.getInstance().getManager().getTransaction();
            transaction.begin();
        }
    }

    public SaveOnCloseDialog(JDialog parent, boolean modal) {
        super(parent, modal);
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosed(java.awt.event.WindowEvent evt) {
                ok = false;
                setVisible(false);
            }
        });
        transaction = JPASession.getInstance().getManager().getTransaction();
        try {
            transaction.begin();
        } catch (java.lang.IllegalStateException ex) {
            transaction.rollback();
            transaction = JPASession.getInstance().getManager().getTransaction();
            transaction.begin();
        }
    }

    @Override
    public void setVisible(boolean b) {
        if (!b) {
            if (isOk()) {
                saveChanges();
            } else {
                rollbackChanges();
            }
        }
        super.setVisible(b);
    }

    private void rollbackChanges() {
        try {
            transaction.rollback();
        } catch (Exception ex) {
            Logger.getLogger(SaveOnCloseDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void saveChanges() {
        try {

            saveNewObjects();
            //JPASession.getInstance().getManager().persist(currentObj);
            transaction.commit();
        } catch (Exception ex) {
            Logger.getLogger(SaveOnCloseDialog.class.getName()).log(Level.SEVERE, null, ex);
            transaction.rollback();
        }
    }

    public boolean isOk() {
        return ok;
    }

    protected abstract void saveNewObjects();
}
